package com.lc.luzhengtang.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.EvaluateListAdapter2;
import com.lc.luzhengtang.banner.BannerLayout;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.CommenCollectBean;
import com.lc.luzhengtang.bean.ShopDetailBean;
import com.lc.luzhengtang.conn.Conn;
import com.lc.luzhengtang.conn.ConnAddShop;
import com.lc.luzhengtang.conn.ConnCancelCollect2;
import com.lc.luzhengtang.conn.ConnShopCollect;
import com.lc.luzhengtang.conn.ConnShopDetail;
import com.lc.luzhengtang.conn.ConnShopDetailWeb;
import com.lc.luzhengtang.fragment.IndexWebActivity;
import com.lc.luzhengtang.glide.GlideImageLoader;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.view.GlideCircleTransform;
import com.lc.luzhengtang.view.goodsdetail.GoodsDetailParent2;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/3.
 */
public class ShopDetailActivity extends BaseActivity {

    @BindView(R.id.banner2)
    BannerLayout banner2;
    @BindView(R.id.img_btn_fanhiu)
    ImageView imgBtnFanhiu;
    @BindView(R.id.img_goto_shop)
    ImageView imgGotoShop;
    @BindView(R.id.img_help)
    ImageView imgHelp;
    @BindView(R.id.search_all_payorder)
    RelativeLayout searchAllPayorder;
    @BindView(R.id.layout_commit)
    RelativeLayout layoutCommit;
    @BindView(R.id.ll_pull_up)
    LinearLayout llPullUp;
    @BindView(R.id.layout_collect)
    LinearLayout layoutCollect;
    @BindView(R.id.joininshopcar)
    TextView joininshopcar;
    @BindView(R.id.text_buyrightnow)
    TextView textBuyrightnow;
    @BindView(R.id.text_collect)
    TextView textCollect;
    @BindView(R.id.layout_cancel_collect)
    LinearLayout layoutCancelCollect;
    @BindView(R.id.layout_share)
    LinearLayout layoutShare;
    private String shop_id;
    String picurl;
    @BindView(R.id.text_title)
    TextView textTitle;
    @BindView(R.id.text_money)
    TextView textMoney;
    @BindView(R.id.text_order_pay)
    TextView textOrderPay;
    String yunfei;
    @BindView(R.id.text_xiaoliang)
    TextView textXiaoliang;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    //    EvaluateListAdapter indexAdapter;
    List<ShopDetailBean.DataBeanX.EvaluateBean.DataBean> mDatas2 = new ArrayList<>();
    EvaluateListAdapter2 evaluateListAdapter2;
    private PopupWindow popWindow;
    private PopupWindow popWindow2;
    public static final String TURN_TO_CART = "turn_to_cart";
    @BoundView(R.id.sv_container)
    GoodsDetailParent2 container;
    @BoundView(R.id.view_lines)
    View view_lines;

    //    layout_scrollview_second
    /*@BoundView(R.id.scrollview)
    GradationScrollView scrollview;*/
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopdetail_zhantie2);
        ButterKnife.bind(this);
      /*  if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this,mPermissionList,123);
        }*/
        shop_id = getIntent().getStringExtra("goods_id");
        getData();


//        container = new ScrollViewContainer(getApplicationContext());
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //支持插件
//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        getWebData();
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setNestedScrollingEnabled(false);
        mShareListener = new ShopDetailActivity.CustomShareListener(this);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(ShopDetailActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,SHARE_MEDIA.QQ
        )

                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copy")) {
                            Toast.makeText(ShopDetailActivity.this, "复制文本按钮", Toast.LENGTH_LONG).show();
                        } else if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Toast.makeText(ShopDetailActivity.this, "复制链接按钮", Toast.LENGTH_LONG).show();

                        } else if (share_media == SHARE_MEDIA.SMS) {
                            new ShareAction(ShopDetailActivity.this).withText("来自分享面板标题")
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();
                        } else {
                            UMWeb web = new UMWeb("http://luzhengtang.cn/index.php/mobile/goods/details?id=" + shop_id);
                            web.setTitle("清君堂");
                            web.setDescription("商品详情");
//                            web.setThumb(new UMImage(ShopDetailActivity.this, R.mipmap.logo));
                            new ShareAction(ShopDetailActivity.this).withMedia(web)
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();
                        }
                    }
                });


        if (shop_id.equals(BaseApplication.basePreferences.getIsCollect())) {
            layoutCancelCollect.setVisibility(View.VISIBLE);
            layoutCollect.setVisibility(View.GONE);
        } else {
            layoutCancelCollect.setVisibility(View.GONE);
            layoutCollect.setVisibility(View.VISIBLE);
        }

    }


    private static class CustomShareListener implements UMShareListener {

        private WeakReference<ShopDetailActivity> mActivity;

        private CustomShareListener(ShopDetailActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
//                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

//            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }


    public void getData() {
        new ConnShopDetail(shop_id, BaseApplication.basePreferences.readUid(), 1, new AsyCallBack<ShopDetailBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                showLoading();
            }

            @Override
            public void onSuccess(String toast, int type, Object o, ShopDetailBean shopDetailBean) throws Exception {
                super.onSuccess(toast, type, o, shopDetailBean);
//                mDatas2 = shopDetailBean.getData().getEvaluate();
                mDatas2 = shopDetailBean.getData().getEvaluate().getData();
                if (mDatas2.isEmpty()) {
                    rvList.setVisibility(View.GONE);
//                    layoutContainrecycleview.setVisibility(View.GONE);
                    view_lines.setVisibility(View.GONE);

                }

                if (shopDetailBean.getData().getHas().equals("1")) {
                    layoutCollect.setVisibility(View.GONE);
                    layoutCancelCollect.setVisibility(View.VISIBLE);
                } else {
                    layoutCollect.setVisibility(View.VISIBLE);
                    layoutCancelCollect.setVisibility(View.GONE);
                }


                evaluateListAdapter2 = new EvaluateListAdapter2(ShopDetailActivity.this, mDatas2);


                List<String> urls = new ArrayList<>();
                final List<String> urlspic = new ArrayList<String>();
                urls = shopDetailBean.getData().getGoodsinfo().getPicarr();
                for (int i = 0; i < urls.size(); i++) {
                    urlspic.add(Conn.HOST2 + urls.get(i));
                }

                picurl = shopDetailBean.getData().getGoodsinfo().getPicarr().get(0);
                banner2.setImageLoader(new GlideImageLoader());
                banner2.setViewUrls(urlspic);
                final List<String> finalUrls = urls;
                banner2.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        //Toast.makeText(ShopDetailActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent();

                        //intent.putExtra("url", urlspic.get(position));
                        intent.putExtra("position", position);
                        intent.putStringArrayListExtra("mImages", (ArrayList<String>) urlspic);
                        intent.setClass(ShopDetailActivity.this, PhotoShowActivity.class);
//                        startActivity(intent);

                    }
                });

                textTitle.setText(shopDetailBean.getData().getGoodsinfo().getTitle());
                textMoney.setText("￥" + shopDetailBean.getData().getGoodsinfo().getSales());
                textOrderPay.setText("运费：" + shopDetailBean.getData().getGoodsinfo().getPostage() + "元");
                yunfei = shopDetailBean.getData().getGoodsinfo().getPostage();
                textXiaoliang.setText("销量：" + shopDetailBean.getData().getGoodsinfo().getVolume());

 /*               indexAdapter = new EvaluateListAdapter(mDatas2);
                indexAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);*/

                rvList.setAdapter(evaluateListAdapter2);

                title_sales = shopDetailBean.getData().getGoodsinfo().getSales();
                text_title = shopDetailBean.getData().getGoodsinfo().getTitle();

                container.setLoadState(true);
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                dismissLoading();
                webView.loadUrl(Conn.HOST2 + "/index.php/api/goods/service?goods_id=" + shop_id);
            }
        }


        ).execute(ShopDetailActivity.this, false);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    public void getWebData() {
        new ConnShopDetailWeb(shop_id, new AsyCallBack<CommenBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);

//
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }

        ).execute(ShopDetailActivity.this, false);
    }

    private UMShareListener mShareListener;
    private ShareAction mShareAction;

    @OnClick({R.id.img_btn_fanhiu, R.id.img_goto_shop, R.id.img_help, R.id.search_all_payorder, R.id.layout_commit, R.id.ll_pull_up, R.id.layout_collect, R.id.joininshopcar, R.id.text_buyrightnow, R.id.layout_cancel_collect, R.id.layout_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_btn_fanhiu:
                finish();
                break;
            case R.id.img_goto_shop:
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(TURN_TO_CART));

                ShopDetailActivity.this.finish();


//                EventBus.getDefault().post(1);
                break;
            case R.id.img_help:
                Intent intent = new Intent();
                intent.putExtra("url", "http://luzhengtang.cn/index.php/api/index/service?web_id=2");
                intent.putExtra("flag", "2");
                intent.setClass(ShopDetailActivity.this, IndexWebActivity.class);
                startActivity(intent);
                break;
            case R.id.search_all_payorder:
                container.content();
                break;
            case R.id.layout_commit:
                Intent intent1 = new Intent();
                intent1.putExtra("shangpin_id", shop_id);
                intent1.setClass(ShopDetailActivity.this, CommentAllActivity2.class);
                startActivity(intent1);
                break;
            case R.id.ll_pull_up:
                break;
            case R.id.layout_collect:
                if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
                    startActivity(new Intent(ShopDetailActivity.this, LoginActivity.class));
                    finish();
                } else {
                    getCollect();
                }

                break;
            case R.id.joininshopcar:
                showPopupWindow(joininshopcar);
                break;
            case R.id.text_buyrightnow:
                showPopupWindow2(textBuyrightnow);
                break;

            case R.id.layout_cancel_collect:
           /*     LovelyToast.makeText(ShopDetailActivity.this, "该商品已收藏", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/

                cancelCollect();
//                getCollect2();
                break;

            case R.id.layout_share:
                mShareAction.open();

                break;

        }
    }

    public void getCollect2() {
        new ConnShopCollect(BaseApplication.basePreferences.readUid(), shop_id, new AsyCallBack<CommenCollectBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenCollectBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);

                if (commenBean.getCode() == 200) {
                    layoutCancelCollect.setVisibility(View.GONE);
                    layoutCollect.setVisibility(View.VISIBLE);
                    BaseApplication.basePreferences.saveIsCollect("");
                    LovelyToast.makeText(ShopDetailActivity.this, "取消收藏成功", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    layoutCancelCollect.setVisibility(View.VISIBLE);
                    layoutCollect.setVisibility(View.GONE);
                    LovelyToast.makeText(ShopDetailActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }
              /*
               LovelyToast.makeText(ShopDetailActivity.this, commenBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                layoutCancelCollect.setVisibility(View.VISIBLE);
                BaseApplication.basePreferences.saveIsCollect(shop_id);
                layoutCollect.setVisibility(View.GONE);*/
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }

        ).execute(ShopDetailActivity.this, false);
    }


    public void cancelCollect() {

        new ConnCancelCollect2(BaseApplication.basePreferences.readUid(), shop_id, new AsyCallBack<CommenBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean collectBean) throws Exception {
                super.onSuccess(toast, type, o, collectBean);
                LovelyToast.makeText(ShopDetailActivity.this, collectBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                if (collectBean.getCode() == 200) {
                    layoutCancelCollect.setVisibility(View.GONE);
                    layoutCollect.setVisibility(View.VISIBLE);
                    BaseApplication.basePreferences.saveIsCollect("");
                } else {
                    layoutCancelCollect.setVisibility(View.VISIBLE);
                    layoutCollect.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                LovelyToast.makeText(ShopDetailActivity.this, "网络访问失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }


        ).execute(ShopDetailActivity.this, false);
    }

    private void showPopupWindow(View parent) {
        if (popWindow == null) {
         /*   View view = LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null);*/
            View view = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private View layout_dismiss;
    String title_sales;
    private String text_title;
    int num = 1;

    public void initPop(View view) {

        TextView tv_02 = (TextView) view.findViewById(R.id.tv_02);

        tv_02.setText("￥" + title_sales);
        ImageView img_pic = (ImageView) view.findViewById(R.id.img_pic);
//
//        Glide.with(ShopDetailActivity.this).load(Conn.HOST3 + getIntent().getStringExtra("img_url")).crossFade().error(R.mipmap.ic_launcher).into(img_pic);
        Glide.with(ShopDetailActivity.this)
                .load(Conn.HOST3 + getIntent().getStringExtra("img_url"))
                .transform(new GlideCircleTransform(ShopDetailActivity.this))
                .error(R.mipmap.zhanwei)
                .placeholder(R.mipmap.zhanwei)
                .into(img_pic);
        TextView tv_01 = (TextView) view.findViewById(R.id.tv_01);
        tv_01.setText(text_title);

        final EditText text_num = (EditText) view.findViewById(R.id.text_num);
        text_num.setSelection(text_num.length());
        layout_dismiss = view.findViewById(R.id.layout_dismiss);
        layout_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
                num=1;
                text_num.setText("1");
            }
        });
        text_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        text_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (TextUtils.isEmpty(text_num.getText().toString())) {
                    num = 0;

                    LovelyToast.makeText(ShopDetailActivity.this, "最小数量不能为0", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (Integer.valueOf(text_num.getText().toString()) < 1) {
                    LovelyToast.makeText(ShopDetailActivity.this, "最小数量不能为0", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    num = Integer.valueOf(text_num.getText().toString());
                }


            }
        });
        //修改数量
        LinearLayout layout_countjia = (LinearLayout) view.findViewById(R.id.layout_countjia);
        layout_countjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = num + 1;
                text_num.setText(num + "");
            }
        });

        LinearLayout layout_jian = (LinearLayout) view.findViewById(R.id.layout_jian);
        if (num < 1) {
            LovelyToast.makeText(ShopDetailActivity.this, "商品数量不能为负数", 0, LovelyToast
                    .SUCCESS, LovelyToast.SCALE);
        } else {
            layout_jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                 /*   num=num-1;
                    text_num.setText(num + "");*/
                    if (num <= 1) {

                    } else {
                        num = num - 1;
                        text_num.setText(num + "");
                    }

                }
            });

        }

        //加入购物车
        final TextView tv_03 = (TextView) view.findViewById(R.id.tv_03);

        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
            startActivity(new Intent(ShopDetailActivity.this, LoginActivity.class));
            finish();
        }

        tv_03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(num) < 1) {
                    LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(tv_03.getText().toString())) {
                    LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    new ConnAddShop(shop_id, BaseApplication.basePreferences.readUid(), num + "", "盒", title_sales, new AsyCallBack<CommenBean>() {
                        @Override
                        public void onStart(int type) throws Exception {
                            super.onStart(type);
                        }

                        @Override
                        public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                            super.onSuccess(toast, type, o, commenBean);
                            LovelyToast.makeText(ShopDetailActivity.this, commenBean.getMessage(), 0, LovelyToast
                                    .SUCCESS, LovelyToast.SCALE);
                            popWindow.dismiss();
                            num=1;

                        }

                        @Override
                        public void onFail(String toast, int type) throws Exception {
                            super.onFail(toast, type);
                        }

                        @Override
                        public void onEnd(String toast, int type) throws Exception {
                            super.onEnd(toast, type);
                        }
                    }


                    ).execute(ShopDetailActivity.this, false);
                }

            }
        });
    }

    public void getCollect() {
        new ConnShopCollect(BaseApplication.basePreferences.readUid(), shop_id, new AsyCallBack<CommenCollectBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenCollectBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getData() == 1) {
                    LovelyToast.makeText(ShopDetailActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    layoutCollect.setVisibility(View.GONE);
                    layoutCancelCollect.setVisibility(View.VISIBLE);
                } else {

                }


//                BaseApplication.basePreferences.saveIsCollect(shop_id);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }

        ).execute(ShopDetailActivity.this, false);
    }

    private void showPopupWindow2(View parent) {
        if (popWindow2 == null) {
            View view1 = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo3, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow2 = new PopupWindow(view1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop2(view1);
        }
        //设置动画效果
        popWindow2.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow2.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow2.setOutsideTouchable(true);
        popWindow2.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow2.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop2(View view1) {
       /**/
        final BigDecimal num1 = new BigDecimal(Double.valueOf(title_sales));
        BigDecimal num2 = new BigDecimal(Double.valueOf(yunfei));
        BigDecimal b3 = num1.subtract(num2);
        BigDecimal b4 = num1.add(num1);
        String total = b4.toString();


//        System.out.println(b1.add(b2));


        TextView tv_02 = (TextView) view1.findViewById(R.id.tv_02);
        tv_02.setText("￥" + title_sales);
        ImageView img_pic = (ImageView) view1.findViewById(R.id.img_pic);


//        Glide.with(ShopDetailActivity.this).load(Conn.HOST3 + getIntent().getStringExtra("img_url")).crossFade().error(R.mipmap.ic_launcher).into(img_pic);
        Glide.with(ShopDetailActivity.this)
                .load(Conn.HOST3 + getIntent().getStringExtra("img_url"))
                .transform(new GlideCircleTransform(ShopDetailActivity.this))
                .error(R.mipmap.zhanwei)
                .placeholder(R.mipmap.zhanwei)
                .into(img_pic);
        TextView tv_01 = (TextView) view1.findViewById(R.id.tv_01);
        tv_01.setText(text_title);


//购买的
        final TextView tv_03 = (TextView) view1.findViewById(R.id.tv_03);
        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
            startActivity(new Intent(ShopDetailActivity.this, LoginActivity.class));
            finish();
        } else {
            tv_03.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Integer.valueOf(num) < 1) {
                        LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    } else if (TextUtils.isEmpty(String.valueOf(num))) {
                        LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    } else if (TextUtils.isEmpty(tv_03.getText().toString())) {
                        LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    } else if (tv_03.getText().toString().equals("0")) {
                        LovelyToast.makeText(ShopDetailActivity.this, "商品数量最小为1", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    } else {
                        Intent intent2 = new Intent();
                        intent2.putExtra("cart_id", shop_id);
                        intent2.putExtra("num", num + "");
                        intent2.putExtra("he", "盒");
                        intent2.setClass(ShopDetailActivity.this, ConfirmOrderActivity2.class);
                        startActivity(intent2);
                        popWindow2.dismiss();
                    }
                }
            });
        }

        final EditText text_num = (EditText) view1.findViewById(R.id.text_num);
        text_num.setSelection(text_num.length());
        //修改数量
        LinearLayout layout_countjia = (LinearLayout) view1.findViewById(R.id.layout_countjia);
        layout_countjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = num + 1;
                text_num.setText(num + "");
            }
        });
        LinearLayout layout_jian = (LinearLayout) view1.findViewById(R.id.layout_jian);
        if (num < 1) {
          /*  LovelyToast.makeText(ShopDetailActivity.this, "商品数量不能为负数", 0, LovelyToast
                    .SUCCESS, LovelyToast.SCALE);*/
        } else {
            layout_jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (num <= 1) {

                    } else {
                        num = num - 1;
                        text_num.setText(num + "");
                    }
                }
            });
        }
        text_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (TextUtils.isEmpty(text_num.getText().toString())) {
                    num = 0;
                    LovelyToast.makeText(ShopDetailActivity.this, "最小数量不能为0", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (Integer.valueOf(text_num.getText().toString()) < 1) {
                    LovelyToast.makeText(ShopDetailActivity.this, "最小数量不能为", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    num = Integer.valueOf(text_num.getText().toString());
                }
            }
        });

        layout_dismiss = view1.findViewById(R.id.layout_dismiss);
        layout_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow2.dismiss();
                num=1;
                text_num.setText("1");
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);//完成回调
    }

}
